package practise;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

public class APIResponse {
	
	public enum Status {
		SUCCESS, ERROR_LOGIN_REQUIRED, ERROR_INVALID_USER, ERROR_INSUFFICIENT_PERMISSION, 
		ERROR_RESOURCE_DOES_NOT_EXIST, ERROR_RESOURCE_ALREADY_EXISTS,
		ERROR_RESOURCE_NOT_FULLY_SPECIFIED, ERROR_UNHANDLED_EXCEPTION, 
	}
	
	public Status statusCode;
	public String userFriendlyMessage;	
	public Object object;
	public Date timeStamp = new Date();
		
	public APIResponse(Status statusCode, Object object) {
		this.statusCode = statusCode;		
		this.object = object;
	}
	
	public APIResponse() {
	}
	
	public APIResponse(Exception ex) {
						
		if (ex instanceof APIException) {
			APIException re = (APIException)ex;
			statusCode = re.statusCode;
			userFriendlyMessage = re.userFriendlyMessage;
		} else {
			statusCode = Status.ERROR_UNHANDLED_EXCEPTION;
			userFriendlyMessage = "Unhandled exception. Please inform the development team";
		}
		
		object = "Stack trace: \n" + stackTraceToString(ex);						
	}
	
	private String stackTraceToString(Throwable e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		
		return sw.toString();
	}		
}
